package com.cskaoyan.shiro;

import com.cskaoyan.util.StringUtil;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author 楚夏三分
 * @datetime 2023/1/1 11:39
 * @description: TODO: SessionManager会话管理器解决跨域场景下的Session变化问题
 */
@Component
public class CustomMarketSessionManager extends DefaultWebSessionManager {
    // 后台管理特定请求头的值(即SessionID)
    private static final String MARKET_ADMIN_TOKEN = "X-CskaoyanMarket-Admin-Token";
    // 微信小程序特定请求头的值(即SessionID)
    private static final String MARKET_WX_TOKEN = "X-CskaoyanMarket-Token";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        // 转换成HTTPServletRequest, 以获取特定请求头
        HttpServletRequest req = (HttpServletRequest)request;

        String sessionId = req.getHeader(MARKET_ADMIN_TOKEN);
        if (!StringUtil.isEmpty(sessionId)){
            return sessionId;
        }
        String sessionId2 = req.getHeader(MARKET_WX_TOKEN);
        if (!StringUtil.isEmpty(sessionId2)){
            return sessionId2;
        }
        return super.getSessionId(request, response);
    }
}
